from flask import Blueprint, jsonify, request

import api.apps.service.user_service as userService
from api.apps.models import user_mapper
from api.apps.log.diy_log import logger

user_controller = Blueprint('user', __name__)


@user_controller.route('/login', methods=['GET'])
def login():
    res = userService.login()
    logger.debug('开始登录！')
    return res

@user_controller.route('/logout', methods=['GET'])
def logout():
    res = userService.logout()
    logger.debug("开始退出登录！")
    return res
@user_controller.route('/addUser', methods=['POST'])
def addUser():
    res = user_mapper.get_user_mapper().create_user(request.json.get('username'), request.json.get('email'),request.json.get('password'))
    print(res.to_dict())
    return jsonify(res.to_dict()), 200  # 返回一个 JSON 响应和状态码
@user_controller.route('/getUserbyUserName', methods=['GET'])
def getUserbyUserName():
    res = user_mapper.get_user_mapper().get_user_by_username(request.args.get('username'))
    print(res.to_dict())
    return jsonify(res.to_dict()), 200  # 返回一个 JSON 响应和状态码

@user_controller.route('/deleteById', methods=['POST'])
def deleteById():
    res = user_mapper.get_user_mapper().delete_user(request.json.get('id'))
    logger.debug(res.id+"删除成功！")
    return jsonify({
        "code": 200,
        "message": "删除成功",
        "data": res.to_dict()
    }), 200  # 返回一个 JSON 响应和状态码

@user_controller.route('/deleteByUsername', methods=['POST'])
def deleteByUsername():
    try:
        res = user_mapper.get_user_mapper().delete_user_byusername(request.json.get('username'))
        if res is not None:
            logger.debug(res.username+"删除成功！")
        else:
            logger.debug("用户不存在！")
            return jsonify({
                "code": 500,
                "message": "删除失败",
                "data": None
            })
    except Exception as e:
        logger.debug(e)
        return jsonify({
            "code": 500,
            "message": "删除失败",
            "data": None
        }), 500
    return jsonify({
        "code": 200,
        "message": "删除成功",
        "data": res.to_dict()
    }), 200  # 返回一个 JSON 响应和状态码


@user_controller.route('/updateUserbyUserName', methods=['POST'])
def updateUser():
    res = user_mapper.get_user_mapper().update_user( request.json.get('username'), request.json.get('email'), request.json.get('password'))
    print(res.to_dict())
    return jsonify({
        "code": 200,
        "message": "更新成功",
        "data": res.to_dict()
    }), 200  # 返回一个 JSON 响应和状态码

